<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-row type="flex" justify="end">
          <a-col>
            <a-button type="primary" @click="showModal(undefined, 1)">新增一级分类</a-button>
          </a-col>
        </a-row>
        <!-- <a-row type="flex" justify="space-between" style="margin: 0 0 10px 0 ">
          <a-col>
            <a-button type="danger" @click="toDelete" :disabled="!hasSelected">删除</a-button>
          </a-col>
        </a-row> -->
      </div>
      <!-- List--table -->
      <a-table 
        :loading="loading"
        :columns="columns" 
        :data-source="tableList" 
        bordered 
        :pagination="pagination"
        :rowKey="(record) => record.id"
         >
        <span slot="edit" slot-scope="text, record">
          <a v-if="record.hideAdd" @click="showModal(record, record.addIndex)" class="mr-15">新增</a>
          <a v-if="record.showEdit" @click="showModal(record, record.editIndex)">编辑</a>
          <a-popconfirm title="是否删除该产品分类?" ok-text="是" cancel-text="否" @confirm="DeleteOne(record)" @cancel="cancelDel">
            <a v-if="record.showDel" class="ml-15">删除</a>
          </a-popconfirm>
          <!-- <a v-if="record.parentId && record.hideAdd" @click="showModal(record,-1)">新增</a>
          <a v-if="record.parentId && record.showEdit" @click="showModal(record,1*1)" class="mr-15">编辑</a>
          <a v-if="showDel" @click="DeleteOne(record)">删除</a> -->
        </span>
      </a-table>
      <!-- 新增/编辑modal -->
      <a-modal :model="form" v-model="visible" :title="title" ok-text="提交" cancel-text="关闭" @cancel="cancel" @ok="onSubmit" :width="800">
        <a-form-model :label-col="{span:5}" :wrapper-col="{span:15}" ref="ruleForm" :model="form" :rules="rules">
          <a-form-model-item label="产品一级分类名称" prop="productOneCategory" v-if="index !== 1 && index !== 4">
            <a-select placeholder="请选择" v-model="form.productOneCategory" @change="value => handleChange(value)" :disabled="index <= 3">
              <a-select-option value="">请选择</a-select-option>
              <a-select-option v-for="(item, index) in selectType" :key="index" :value="item.id">
                {{ item.categoryName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="产品二级分类名称" prop="productSecondCategory" v-if="index === 3 || index === 6">
            <a-select placeholder="请选择" v-model="form.productSecondCategory" @change="handleChange1" :disabled="form.productOneCategory === '' || index <= 3">
              <a-select-option value="">请选择</a-select-option>
              <a-select-option v-for="(item, index) in selectTypeTwo" :key="index" :value="item.id">
                {{ item.categoryName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>   
          <a-form-model-item label="产品分类名称" prop="categoryName">
            <a-input v-model="form.categoryName"></a-input>
          </a-form-model-item>
          <a-form-model-item label="产品分类编号" prop="categoryNo">
            <a-input v-model="form.categoryNo"></a-input>
          </a-form-model-item>
          <a-form-model-item label="产品分类状态" prop="categoryStatus" class="status-cls">
            <!-- 单选框 -->
            <a-radio-group v-model="form.categoryStatus">
              <a-radio v-for="item in typeStatus" :key="item.value" :value="item.value">{{ item.label }}</a-radio>
            </a-radio-group>
            <!-- 选择框 -->
            <!-- <a-select placeholder="请选择" v-model="form.categoryStatus">
              <a-select-option v-for="item in typeStatus" :key="item.value" :value="item.value">
                {{ item.label }}
              </a-select-option>
            </a-select> -->
          </a-form-model-item>
        </a-form-model>
        <!-- <a-form-model ref="ruleForm" :model="form" :rules="rules" layout="inline" align="center">
          <a-form-model-item label="产品一级分类：" prop="productOneCategory">
            <a-select placeholder="请选择" v-model="form.productOneCategory" @change="handleChange" style="width: 500px" disabled>
              <a-select-option value="">请选择</a-select-option>
              <a-select-option v-for="(item, index) in selectType" :key="index" :value="item.id">
                {{ item.categoryName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="产品二级分类：" prop="productSecondCategory">
            <a-select placeholder="请选择" v-model="form.productSecondCategory" @change="handleChange1" style="width: 500px" :disabled="showSelected">
              <a-select-option value="">请选择</a-select-option>
              <a-select-option v-for="(item, index) in selectTypeTwo" :key="index" :value="item.id">
                {{ item.categoryName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>     
          <a-form-model-item label="三级类别名称：" prop="categoryName">
            <a-input v-model="form.categoryName" style="width: 500px"></a-input>
          </a-form-model-item><br>
          <a-form-model-item prop="status">
            状态：<a-switch checked-children="正常" un-checked-children="停用" v-model="form.status" />
          </a-form-model-item>
        </a-form-model> -->
      </a-modal>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import { GetProductCategoryTree,DeleteProductCategory,getProductOneCategory,AddProductCategory,UpdateProductCategory } from "@/api/product"
export default {
  data() {
    let checkCategoryName = (rule, value, callback) => {
      if(value === '') {
        callback(new Error('请输入分类名称'))
      }else {
        let isSimpleId = this.productList.find(ele => this.form.id !== ele.id && value === ele.categoryName)
        typeof isSimpleId !== 'undefined' ? callback(new Error('该分类名称已存在')) : callback()
      }
    }
    let checkCategoryNo = (rule, value, callback) => {
      if(value === '') {
        callback(new Error('请输入分类编号'))
      }else {
        let isSimpleId = this.productList.find(ele => this.form.id !== ele.id && value === ele.categoryNo)
        typeof isSimpleId !== 'undefined' ? callback(new Error('该分类编号已存在')) : callback()
      }
    }
    return {
      showSelected:false,
      loading: false,
      rules: {
        categoryName: [{ required: true, validator: checkCategoryName, trigger: 'blur' }],
        categoryNo: [{ required: true, validator: checkCategoryNo, trigger: 'blur' }],
        productOneCategory: [{ required: true, message: '请选择一级分类', trigger: 'blur' }],
        productSecondCategory: [{ required: true, message: '请选择二级分类', trigger: 'blur' }]
        // categoryName: [{ required: true, message: '请输入三级类别名称', trigger: 'blur' }],
      },
      parentId:'',      //二级产品分类ID
      thirdId: '',   //三级Id
      // categoryNameThird:'',   //三级分类
      // delIds:'',  //删除的Ids
      // selectedRowKeys: [], //列表选择key集合
      productList:[],
      tableList:[],
      selectType:[], //产品分类一级
      selectTypeTwo:[], //产品分类二级
      pagination: {
        total: 0,
        pageSize: 10,
        current: 1,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '30', '40', '50'],
        showTotal: (total) => `共有 ${total} 条数据`,
        showQuickJumper: true,
        onShowSizeChange: (current, pageSize) => this.onSizeChange(current, pageSize),
        onChange: (page, pageSize) => this.onPageChange(page, pageSize),
      },
      typeStatus: [
        {
          label: '停用',
          value: 0
        },
        {
          label: '正常',
          value: 1
        }
      ],
      columns: [
        {
          title: '一级分类名称',
          dataIndex: 'categoryName',
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          align: 'center',
        },
        {
          title: '操作',
          dataIndex: 'edit',
          align: 'center',
          scopedSlots: { customRender: 'edit' },
        },
      ],
      visible: false,
      activeName: '',
      productOneCategory:'',
      form:{
        // keyword: '',
        id: '',
        productOneCategory: '',
        productSecondCategory: '',
        categoryNo: '',
        categoryName: '',
        categoryStatus: 1
      },
      index: 0,
      deleteIds:''
    }
  },
  created(){
    this.toGetProductCategoryTree()
    this.GetByParentList();
  },
  methods: {
    //获取产品分类管理列表
    toGetProductCategoryTree(){
      let params ={
        current: this.pagination.current,
        size: this.pagination.pageSize,
      }
      this.loading = true
      function* gen(nodes = []) {
        for(let item of nodes) {
          yield item
          if(item.children && item.children.length) yield* gen(item.children)
        }
      }
      GetProductCategoryTree(params).then(res=>{
        if(res.code == 200){
          this.loading = false
          res.data.map(items =>{
            // 一级
            this.$set(items, 'hideAdd', true)
            this.$set(items, 'showEdit', true)
            this.$set(items, 'addIndex', 2)
            this.$set(items, 'editIndex', 4)
            this.$set(items, 'level', 1)
            items.children.map(item => {
              // 二级
              this.$set(item, 'hideAdd',true)
              this.$set(item, 'showEdit',true)
              this.$set(item, 'addIndex', 3)
              this.$set(item, 'editIndex', 5)
              this.$set(item, 'level', 2)
              if(item.children.length>0){
                // 三级
                item.children.map(obj =>{
                obj['OneAndTwoName'] = items.categoryName +','+item.categoryName
                  this.$set(obj, 'showEdit', true)
                  this.$set(obj, 'showDel', true)
                  this.$set(obj, 'editIndex', 6)
                  this.$set(obj, 'level', 3)
                })
              }
            })
          })
          this.tableList = res.data
          this.productList = [...gen(this.tableList)]
        }
      })
    },
    //变更每页条数
    onSizeChange(current, size) {
      this.pagination.current = current
      this.pagination.pageSize = size
      this.toGetProductCategoryTree()
    },
    //翻页
    onPageChange(page, pageSize) {
      this.pagination.current = page
      this.toGetProductCategoryTree()
    },
    // 产品一级分类下拉列表
    GetByParentList() {
      getProductOneCategory().then((res) => {
        if (res.code == 200) {
          this.selectType = res.data;
        }
      });
    },
    // 一级菜单触发
    handleChange(value, secondCategory = '') {
      this.selectType.map((item, index) => {
        if (item.id == value) {
          this.productOneCategory = item.categoryNo.trim();
        }
      });
     
      let params = { pid: value };
      getProductOneCategory(params).then((res) => {
        if (res.code == 200) {
          // console.log(this.form.productSecondCategory);
          this.form.productSecondCategory = secondCategory
          this.selectTypeTwo = res.data
        }
      });
    },
    // 二级菜单触发
    handleChange1(value) {
      // this.parentId = value
      let _searchProductCategory2List = localStorage.getItem(
        "searchProductCategory2List"
      );
      let searchProductCategory2List = [];
      if (_searchProductCategory2List) {
        // 获取本地产品 关键字记录
        searchProductCategory2List = JSON.parse(_searchProductCategory2List);
        if (searchProductCategory2List.length >= 5) {
          searchProductCategory2List.shift();
        }
        searchProductCategory2List.push(value);
      } else {
        searchProductCategory2List.push(value);
      }
      localStorage.setItem(
        "searchProductCategory2List",
        JSON.stringify(searchProductCategory2List)
      );
    },
    // 选择操作
    // onSelectChange(value,selectedRowKeys) {
    //   this.selectedRowKeys = value
    //   this.deleteIds = selectedRowKeys.map(item=>item.id).join(',')   //删除或批量删除的Id
    // },
    // 新增/编辑弹窗
    showModal(record, index) {
      this.visible = true
      this.index = index
      this.form = this.$options.data().form
      if(index === 2) {
        this.form.productOneCategory = record.id
      }else if(index === 3) {
        this.form.productOneCategory = record.parentId
        this.form.productSecondCategory = record.id
      }else if(index > 3) {
        this.form.id = record.id
        this.form.categoryName = record.categoryName
        this.form.categoryNo = record.categoryNo
        this.form.categoryStatus = record.categoryStatus
        if(record.parentId !== null) {
          for(let item of this.productList) {
            if(item.id == record.parentId && index === 6) { // 三级菜单回显
              this.form.productOneCategory = item.parentId
              this.form.productSecondCategory = item.id
              break
            }else if(item.id == record.parentId && index === 5) { // 二级菜单回显
              this.form.productOneCategory = item.id
              break
            }
          }
        }
      }
      this.handleChange(this.form.productOneCategory, this.form.productSecondCategory)
      // console.log(record, index)
      // this.showSelected=true
      // if(index > 0){
      //   // 编辑 => record => 三级
      //   this.thirdId = record.id
      //   let arrNames = record.OneAndTwoName.split(',')
      //   this.form.productOneCategory = arrNames[0]
      //   this.form.productSecondCategory = arrNames[1]
      //   this.form.categoryName = record.categoryName         //三级回显
      //   this.index = index
      // }else{
      //   // 新增  => 通过二级找一级(已有数据)
      //   this.parentId = record.id
      //   this.selectType.map((item, index) => {
      //     if (item.id == record.parentId) {
      //       this.form.productOneCategory = item.categoryName
      //       this.form.productSecondCategory = record.categoryName
      //     }
      //   });
      //   this.form.categoryName = ''
      //   this.index = index
      // }
      // this.visible = true
    },
    // 确定新增/编辑
    // UpdateProductCategory
    onSubmit(e) {
      e.preventDefault();
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          // 相同id校验
          // let isSimpleId = undefined
          // if(this.index === 1 || this.index === 4) {  // 一级菜单
          //   isSimpleId = this.productList.find(ele => ele.level === 1 && this.form.categoryNo === ele.categoryNo && this.form.id !== ele.id)
          // }else if(this.index === 2 || this.index === 5) {  // 二级菜单
          //   isSimpleId = this.productList.find(ele => ele.level === 2 && this.form.categoryNo === ele.categoryNo && this.form.id !== ele.id)
          // }else if(this.index === 3 || this.index === 6) {  // 三级菜单
          //   isSimpleId = this.productList.find(ele => ele.level === 3 && this.form.categoryNo === ele.categoryNo && this.form.id !== ele.id)
          // }

          // if(typeof isSimpleId === 'undefined') {   // 配置请求参数
            let params = {}
            if(this.index === 1) {  // 新增一级菜单
              params = {
                categoryNo: this.form.categoryNo,
                categoryName: this.form.categoryName,
                categoryStatus: this.form.categoryStatus
              }
            }else if(this.index === 2 || this.index === 3) {  // 新增二、三级菜单
              params = {
                categoryNo: this.form.categoryNo,
                categoryName: this.form.categoryName,
                categoryStatus: this.form.categoryStatus,
                parentId: this.index === 2 ? this.form.productOneCategory : this.form.productSecondCategory
              }
            }else if(this.index === 4) {  // 编辑一级菜单
              params = {
                id: this.form.id,
                categoryNo: this.form.categoryNo,
                categoryName: this.form.categoryName,
                categoryStatus: this.form.categoryStatus
              }
            }else if(this.index === 5 || this.index === 6) {  // 编辑二、三级菜单
              params = {
                id: this.form.id,
                categoryNo: this.form.categoryNo,
                categoryName: this.form.categoryName,
                categoryStatus: this.form.categoryStatus,
                parentId: this.index === 5 ? this.form.productOneCategory : this.form.productSecondCategory
              }
            }

            if(this.index <= 3) {  // 新增
              AddProductCategory(params).then(res => {
                if(res.code === 200) {
                  this.$message.success('新增成功')
                  this.toGetProductCategoryTree()
                  this.GetByParentList()
                  this.visible = false
                }else {
                  this.$message.error('新增失败')
                }
              })
            }else if(this.index >= 4) {
              UpdateProductCategory(params).then(res => {
                if(res.code == 200){
                  this.$message.success('修改成功')
                  this.toGetProductCategoryTree()
                  this.GetByParentList()
                  this.visible = false
                }else {
                  this.$message.error('修改失败')
                }
              })
            }
          // }else {
          //   this.$message.error('分类编号或名称已存在，请重新输入')
          // }
          
          
        //   if(this.index > 0){
        //     // 编辑
        //     let params = {
        //       categoryName: this.form.categoryName,
        //       id: this.thirdId,
        //     }
        //     UpdateProductCategory(params).then(res =>{
        //       if(res.code == 200){
        //         this.toGetProductCategoryTree()
        //       }
        //     })
        //   }else{
        //     // 添加
        //     let params = {
        //       categoryName: this.form.categoryName,
        //       parentId: this.parentId
        //     }
        //     AddProductCategory(params).then(res =>{
        //       if(res.code == 200){
        //         this.parentId = ''
        //         this.form.categoryName = ''
        //         this.toGetProductCategoryTree()
        //       }
        //     })
        //   }
        //  this.visible = false
        }
      })
    },
    // // 批量删除或单个删除系统消息
    // toDelete(){
    //   if(this.deleteIds == ''){
    //     return this.$message.error("请先选择哦！")
    //   }else{
    //     let params = { id: this.deleteIds }
    //     DeleteProductCategory(params).then(res => {
    //       if(res.code == 200){
    //         this.selectedRowKeys = []
    //         this.$message.success("删除成功")
    //           if(this.list.length == 1 ){
    //             // 如果只有最后一条就刷新上一页
    //             this.pagination.current--;
    //           }
    //           if(this.pagination.current< 1){
    //             this.pagination.current = 1;
    //           }
    //           this.toGetProductCategoryTree();
    //       }
    //     })
    //   }
    // },
    // 删除单个
    DeleteOne(item){
        let params = { id: item.id }
        DeleteProductCategory(params).then(res => {
          if(res.code == 200){
            if(this.tableList.length == 1 ){
            // 如果只有最后一条就刷新上一页
              this.pagination.current--;
            }
            if(this.pagination.current < 1){
              this.pagination.current = 1;
            }
            this.$message.success("删除成功")
            this.toGetProductCategoryTree();
          }
        })
    },
    // 取消删除
    cancelDel() {},
    // 取消
    cancel(){
      this.$refs.ruleForm.resetFields()
    }
  },
  computed: {
    // hasSelected() {
    //   return this.selectedRowKeys.length > 0;
    // },
    title() {
      let title = ''
      if(this.index === 1) {
        title = '新增一级产品类别'
      }else if(this.index === 2) {
        title = '新增二级产品类别'
      }else if(this.index === 3) {
        title = '新增三级产品类别'
      }else if(this.index === 4) {
        title = '编辑一级产品类别'
      }else if(this.index === 5) {
        title = '编辑二级产品类别'
      }else if(this.index === 6) {
        title = '编辑三级产品类别'
      }
      return title
    }
  },
}
</script>

<style lang="less" scoped>
::v-deep .ant-form-explain {
  text-align: left;
}
.space {
  margin: 40px 0;
}
.nomal {
  width: 50px;
  height: 30px;
  color: #ffffff;
  background-color: #188af1;
  line-height: 30px;
  margin-left: 35%;
  border-radius: 2px;
  transform: scale(1, 0.9);
}
.notNomal {
  width: 50px;
  height: 30px;
  color: #ffffff;
  background-color: #e9284f;
  line-height: 30px;
  margin-left: 35%;
  border-radius: 2px;
  transform: scale(1, 0.9);
}
.table-page-search-wrapper {
  margin-bottom: 20px;
}
.ant-modal {
  .ant-modal-body {
    .status-cls {
      ::v-deep .ant-form-item-control-wrapper {
        width: 30.6%;
      }
    }
  }
}
</style>
